package cn.kgc.ywz.smbms.web.web;

import cn.kgc.ywz.smbms.web.entity.Provider;
import cn.kgc.ywz.smbms.web.service.ProviderService;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
@RequestMapping("/provider")
public class ProviderController {

    @Resource
    private ProviderService providerService;

    /**
     * 查询
     */
    @RequestMapping("/show")
    public String show(Provider condition, Integer pageNum, Integer pageSize, Model model) {
        pageSize = 5;
        PageInfo<Provider> pageInfo = this.providerService.find(condition, pageNum, pageSize);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("condition", condition);
        return "provider/providerlist";
    }

    /**
     * 查看
     */
    @RequestMapping("/toView")
    public String toView(Provider provider, Model model) {
        model.addAttribute("provider", provider);
        return "provider/providerview";
    }

    /**
     * 查询供应商编码是否存在
     */
    @RequestMapping("/doProCode")
    @ResponseBody
    public String doProCode(String proCode) {
        Integer count = this.providerService.findProCode(proCode);
        return count.toString();
    }

    /**
     * 添加
     */
    @RequestMapping("/toAdd")
    public String toAdd() {
        return "provider/provideradd";
    }

    @RequestMapping("/doAdd")
    public String doAdd(@Valid Provider provider, BindingResult result) {
        if (result.hasErrors()) {
            return "provider/provideradd";
        }
        int r = this.providerService.add(provider);
        if (r < 0) {
            return "redirect:toAdd";
        }
        return "redirect:show";
    }

    /**
     * 修改
     */
    @RequestMapping("/toModif")
    public String toModif(Provider provider, Model model) {

        model.addAttribute("provider", provider);
        return "provider/providermodify";
    }

    @RequestMapping("/doModif")
    public String doModif(@Valid Provider provider, BindingResult result) {
        if (result.hasErrors()) {
            return "provider/providermodify";
        }
        int r = this.providerService.update(provider);
        if (r < 0) return "redirect:toModif";
        return "redirect:show";
    }

    /**
     * 删除
     */
    @RequestMapping("/doRemove")
    public void doRemove(Long id, HttpServletResponse response) throws IOException {
        PrintWriter out = response.getWriter();
        int r = this.providerService.remove(id);
        out.print(r);
    }
}
